package com.example.demo.controller;

import com.example.demo.entity.UserInfo;
import com.example.demo.service.LoginService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.time.LocalDateTime;

/**
 * @author vivi
 * @description
 * @date 2024/5/31
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private DataSourceTransactionManager transactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private LoginService loginService;

    @RequestMapping("/add")
    public int add(UserInfo userInfo) {
        // 非空校验
        if (userInfo == null || ! StringUtils.hasLength(userInfo.getUsername())) {
            return 0;
        }

        // 1 开始事务
        TransactionStatus transactionStatus =
                transactionManager.getTransaction(transactionDefinition);

        // 手动设置 创建时间 和 修改时间 的值
        userInfo.setCreatetime(LocalDateTime.now().toString());
        userInfo.setUpdatetime(LocalDateTime.now().toString());

        int result = userService.add(userInfo);
        System.out.println("添加：" + result);

//        // 2 回滚事务
//        transactionManager.rollback(transactionStatus); // 数据库没有添加新用户

        // 3 提交事务
        transactionManager.commit(transactionStatus);

        return result;
    }

    @Transactional(propagation = Propagation.NESTED) // 声明式的 自动提交事务
    @RequestMapping("/insert")
    public Integer insert(UserInfo userInfo) {
        // 非空校验
        if (userInfo == null || ! StringUtils.hasLength(userInfo.getUsername())) {
            return 0;
        }

        // 手动设置 创建时间 和 修改时间 的值
        userInfo.setCreatetime(LocalDateTime.now().toString());
        userInfo.setUpdatetime(LocalDateTime.now().toString());

        int result = userService.add(userInfo);
        if (result > 0) {
            loginService.add();
        }
//        System.out.println("添加：" + result);
//        try {
//            int num = 10/0;
//        } catch (Exception e) {
//            // 将异常继续抛出
////            throw e;
//            System.out.println(e.getMessage());
//            // 手动回滚事务
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//        }

        return result;
    }

}




















